/*
 * 太原科技大学。
 * Copyright 2021, YCHS Information&Science Technology Co.,Ltd,
 * All rights reserved.
 */
package com.example.demo.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.Utils.JWTUtils;
import com.example.demo.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author liuchao
 * @version 1.0
 * @date 2024/5/7
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("运行前运行");
        //1、获取token
        String token=request.getHeader("token");
        System.out.println(token);
        //2、判断token是否为空
        if(token==null||!StringUtils.hasLength(token)){//使用字符串判断工具类判断有长度，说明有值
            log.info("没有登录，请跳转登录");
            //将错误结果以json数据格式返回前端解析
            String noLogin= JSONObject.toJSONString(Result.error("NOT_LOGIN"));
            //响应
            response.getWriter().write(noLogin);
            return false;
        }
        //3、解析token是否正确

        try {
            JWTUtils.getJWT(token).get("username");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("密码或用户名错误，请跳转登录");
            //将错误结果以json数据格式返回前端解析
            String noLogin= JSONObject.toJSONString(Result.error("NOT_LOGIN"));
            //响应
            response.getWriter().write(noLogin);
            return false;
        }

        //4、放行
        log.info("放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("运行后运行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("渲染后运行");
    }
}

